package com.songxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songxh.common.BaseContext;
import com.songxh.common.CustomException;
import com.songxh.mapper.OrderMapper;
import com.songxh.pojo.*;
import com.songxh.service.*;
import com.sun.org.apache.bcel.internal.generic.NEWARRAY;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author songxh
 * @create 2022-04-27-22:04
 */
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 用户提交订单
     *
     * 一共操作三张表，对订单表插入数据，对订单详情表插入详细数据，对购物车表进行删除
     *
     * @param orders
     */
    @Override
    public void submitData(Orders orders) {

        //获取当前用户信息
        Long userId = BaseContext.getCurrentId();
        //查询当前用户购物车数据
        QueryWrapper<ShoppingCart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);//当前用户购物车的内容
        if (list == null || list.size()==0){
            throw new CustomException("购物车为空,不能下蛋");
        }

        //查询用户详细
        User user = userService.getById(userId);

        //查询地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        //向订单表插入数据，一条数据
        long orderId = IdWorker.getId();


        List<OrderDetail> orderDetails= new ArrayList<>();

        AtomicInteger amount=new AtomicInteger(0);//给总金额一个初始值

        //给OrderDetail从购物车中拿出数据然后来赋值
        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setName(cart.getName());
            orderDetail.setImage(cart.getImage());
            orderDetail.setAmount(cart.getAmount());
            amount.addAndGet(cart.getAmount().multiply(new BigDecimal(cart.getNumber())).intValue());

            orderDetails.add(orderDetail);
        }


        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，很详细，可能是多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.remove(queryWrapper);
    }
}
